<template>
    <div class="exam-container">
        <div class="filter-section">
            <div style="display: flex">
                <div style="width: 90px">
                    课程分类:
                </div>
                <el-radio-group v-model="radio">
                    <el-radio>全部</el-radio>
                    <el-radio
                            v-for="item in courseTypeOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                    >
                        <span>{{ item.name }} </span>
                    </el-radio>
                </el-radio-group>
            </div>
            <div class="tab-group">
                <el-tabs v-model="activeName" style="height: 50vh;">
                    <el-tab-pane label="全部" name="first" @tab-click="handleClick">
                        <div class="exam-history-list">
                            <el-table :data="examLists" :row-style="{ height: '60px' }" style="height: 40vh;font-size: 15px;">
                                <el-table-column fixed prop="courseName" label="课程名称" align="center" min-width="80"
                                                 show-overflow-tooltip/>
                                <el-table-column prop="examTotalScore" label="总分" align="center" min-width="50"/>
                                <el-table-column prop="flow" label="是否考试" align="center" width="100">
                                    <template #default="scope">
                                        <el-tag type="warning" v-if="scope.row.flow === 0">未考试</el-tag>
                                        <el-tag type="success" v-else-if="scope.row.flow === 1">已考试</el-tag>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="createTime" label="创建时间" align="center" min-width="100"/>
                                <el-table-column label="操作" fixed="right" align="center" width="100">
                                    <template v-slot="scope">
                                        <el-button v-if="scope.row.flow===0" type="primary" size="small"
                                                   icon="Tickets"
                                                   @click="handleStartExam(scope.row.courseId)">开始考试
                                        </el-button>
                                        <el-button v-if="scope.row.flow===1" type="success" size="small" icon="View"
                                                   @click="toScore(scope.row.courseId)">查看成绩
                                        </el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </el-tab-pane>
                    <el-tab-pane label="未考试" name="second">
                        <div class="exam-history-list">
                            <el-table :data="pendingExams" :row-style="{ height: '60px' }" style="height: 40vh;font-size: 15px;">
                                <el-table-column fixed prop="courseName" label="课程名称" align="center" min-width="80"
                                                 show-overflow-tooltip/>
                                <el-table-column prop="examTotalScore" label="总分" align="center" min-width="50"/>
                                <el-table-column prop="createTime" label="创建时间" align="center" min-width="100"/>
                                <el-table-column label="操作" fixed="right" align="center" width="100">
                                    <template v-slot="scope">
                                        <el-button type="primary" size="small"
                                                   icon="Tickets"
                                                   @click="handleStartExam(scope.row.courseId)">开始考试
                                        </el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </el-tab-pane>
                    <el-tab-pane label="已考试" name="third">
                        <div class="exam-history-list">
                            <el-table :data="historyExams" :row-style="{ height: '60px' }" style="height: 50vh;font-size: 15px;">
                                <el-table-column fixed prop="courseName" label="课程名称" align="center" min-width="80"
                                                 show-overflow-tooltip/>
                                <el-table-column prop="name" label="试卷名称" align="center" min-width="100"
                                                 show-overflow-tooltip/>
                                <el-table-column prop="exampaperDate" label="考试时长(分钟)" align="center" min-width="50"/>
                                <el-table-column prop="exampaperNum" label="试题数量" align="center" min-width="50"/>
                                <el-table-column prop="exampaperAllScore" label="总分" align="center" min-width="50"/>
                                <el-table-column prop="exampaperGetScore" label="成绩" align="center" width="50"/>
                                <el-table-column prop="isPsaa" label="是否及格" align="center" width="100">
                                    <template #default="scope">
                                        <el-tag type="error" v-if="scope.row.isPass === 0">不及格</el-tag>
                                        <el-tag type="success" v-else-if="scope.row.isPass === 1">及格</el-tag>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="createTime" label="创建时间" align="center" min-width="100"/>
                                <el-table-column label="操作" fixed="right" align="center" width="100">
                                    <template v-slot="scope">
                                        <el-button v-if="scope.row.isPass === 0" type="primary" size="small"
                                                   icon="Tickets"
                                                   @click="handleStartExam(scope.row.courseId)">重新考试
                                        </el-button>
                                        <el-button type="success" size="small" icon="View"
                                                   @click="toScore(scope.row.courseId)">查看成绩
                                        </el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </el-tab-pane>
                </el-tabs>
                <!-- 分页组件 -->
                <div style="justify-content: center">
                    <el-pagination
                            :current-page="currentPage"
                            :page-size="pageSize"
                            :page-sizes="[10, 20, 30, 50]"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="total"
                            :background="true"
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                    />
                </div>
            </div>
        </div>
    </div>
    <el-dialog :close-on-click-modal="false" title="拍照" v-model="dialogVisible" :style="dialogStyle1" @close="closeCamera">
        <el-form label-position="top" :inline="true">
            <el-form-item>
                <el-button @click="uploadImage()" type="primary">上传照片</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" title="签名" v-model="dialogVisible1" :style="dialogStyle1" @close="closeSign">
        <div style="width: 100%;text-align: left">
            <Signature :resultImg="resultImg" @updateSignImg="updateSignImg"/>
        </div>
    </el-dialog>
</template>

<script>
    import request from "~/utils/request.js";
    import TakePhotos from '~/components/TakePhotos.vue';
    import Signature from '~/components/Signature.vue';

    export default {
        name: 'ExamPage',
        components: {
            TakePhotos,
            Signature
        },
        data() {
            return {
                windowWidth: window.innerWidth,
                dialogVisible: false,
                dialogVisible1: false,
                resultImg: '',
                showCamera: false, // 控制摄像头组件的显隐
                currentExam: null, // 当前播放的视频信息
                radio: "",
                search: "",  // 搜索框的值
                courseTypeOptions: [],
                activeCategory: '全部',
                activeName: 'first',
                // 签名相关数据
                examSign: {
                    photo: '', // 照片
                    url: '', // 签名
                    courseId: '', // 课程ID
                    stuId: this.$store.state.user.id, // 学员ID
                },
                state: "",
                // 全部列表
                examLists: [],
                // 未考试列表
                pendingExams: [],
                // 已考试列表
                historyExams: [],
                currentPage: 1,
                pageSize: 10,
                total: 0,
                userId:this.$store.state.user.id,

            }
        },
        computed: {
            dialogStyle() {
                return this.windowWidth <= 768 ? { width: '90%' } : { width: '50%' };
            },
            dialogStyle1() {
                return this.windowWidth <= 768 ? { width: '90%' } : { width: '360px' };
            }
        },
        mounted() {
            window.addEventListener('resize', this.handleResize);
        },
        beforeUnmount() {
            window.removeEventListener('resize', this.handleResize);
        },
        activated() {
            this.load()
            this.getCourseTypeOptions()
        },
        watch: {
            radio() {
                this.updateStateAndLoad();
            },
            activeName() {
                this.updateStateAndLoad();
            }
        },
        methods: {
            handleResize() {
                this.windowWidth = window.innerWidth;
            },
            load() {
                this.dialogVisible = false;
                this.dialogVisible1 = false;
                if (this.activeName === "first") {
                    request.get("/exam-log/stuFindExamPage", {
                        params: {
                            pageNum: this.currentPage,
                            pageSize: this.pageSize,
                            name: this.search,
                            typeId:this.radio,
                            userId: this.userId,
                            flow:this.state,

                        }
                    }).then(res => {
                        this.examLists = res.data.records;
                        this.total = res.data.total;
                    })
                }else if (this.activeName === "second") {
                    request.get("/exam-log/stuFindExamPage", {
                        params: {
                            pageNum: this.currentPage,
                            pageSize: this.pageSize,
                            name: this.search,
                            typeId:this.radio,
                            userId: this.userId,
                            flow:this.state,

                        }
                    }).then(res => {
                        this.pendingExams = res.data.records;
                        this.total = res.data.total;
                    })
                }else if (this.activeName === "third") {
                    request.get("/exam-log/stuFindExamPage", {
                        params: {
                            pageNum: this.currentPage,
                            pageSize: this.pageSize,
                            name: this.search,
                            typeId:this.radio,
                            userId: this.userId,
                            flow:this.state,
                        }
                    }).then(res => {
                        this.historyExams = res.data.records;
                        this.total = res.data.total;
                    })
                }

            },
            handleClick(tab) {
                this.activeName = tab.props.name;
            },
            getCourseTypeOptions() {
                request.get("/course-type/all").then(res => {
                    this.courseTypeOptions = res.data
                })
            },
            toScore(scope) {
                this.$router.push({path: "/exam/result", query: {courseId: scope}})
            },
            handleCurrentChange(item) {
                // 改变当前页码触发
                this.currentPage = item
                this.load()
            },
            handleSizeChange(item) {   // 改变当前每页的个数触发
                this.pageSize = item
                this.load()
            },
            async handleStartExam(exam) {
                // 检查是否已学习
                const res = await request.get("/exam-sign/stuFindIsLearned", {
                    params: {
                        courseId: exam,
                        stuId: this.$store.state.user.id,
                    }
                });
                // 检查响应状态和数据
                if (res.code === "200" && res.data.isStudy === false) {
                    this.$message.error("请观看完该课程下的所有课件视频和培训资料后考试");
                    return;
                }

                this.$confirm('是否开始考试?', '提示', {
                    confirmButtonText: '是',
                    cancelButtonText: '否',
                    type: 'warning'
                }).then(async () => {
                    // 传递课程ID作为参数
                    this.examSign.courseId = exam;

                    // // 检查是否已经完成签到
                    // const res = await request.get("/exam-sign/stuFindIsExamSign", {
                    //     params: {
                    //         courseId: exam,
                    //         stuId: this.$store.state.user.id,
                    //     }
                    // });

                    // // 检查响应状态和数据
                    // if (res.code === "200" && res.data.isExamSign === true) {
                    //     this.$router.push({path: "/exam/examPaper", query: {courseId: this.examSign.courseId}})
                    //     return;
                    // }

                    this.dialogVisible = true;
                    this.currentExam = exam;
                    this.showCamera = true; // 显示摄像头组件

                }).catch(() => {
                    // 用户点击否，不做任何操作
                })
            },
            // 根据 activeName 和 state 更新状态并加载数据
            updateStateAndLoad() {
                if (this.activeName === "first") {
                this.state = "";
                } else if (this.activeName === "second") {
                this.state = 0;
                } else if (this.activeName === "third") {
                this.state = 1;
                }
                this.load();
            },

            // 上传图片
            uploadImage() {
                // 创建文件选择输入
                const input = document.createElement('input');
                input.type = 'file';
                input.accept = 'image/*';

                input.onchange = async (e) => {
                    const file = e.target.files[0];
                    if (!file) return;
                    // 上传图片到服务器
                    // 创建FormData并添加文件
                    const formData = new FormData()
                    formData.append('file', file) // 字段名必须与接口参数名一致

                    // 发送请求（根据实际请求库调整）
                    request.post("/files/upload", formData).then(res => {
                        if (res !== null && res !== "") {
                            this.$message.success('上传成功');
                            this.handlePhotoUpload(res)
                        }
                    }).catch(err => {
                        console.error('上传失败:', err)
                    })
                };

                // 触发文件选择对话框
                input.click();
            },
            // 处理拍照完成后的回调
            handlePhotoUpload(url) {
                console.log('照片上传成功:', url);
                this.examSign.photo = `/api/file/download/${url}`
                this.dialogVisible = false
                this.dialogVisible1 = true
            },
            handleCameraClose() {
                // 重置摄像头但不隐藏组件
                if (this.$refs.takePhotosRef) {
                    this.$refs.takePhotosRef.closeCamera();
                }
            },
            updateSignImg(sign) {
                console.log(sign)
                this.examSign.url = `${sign}`
                // 调用接口上传
                request.post("/exam-sign/edit", this.examSign).then(res => {
                    if (res.code === "200") {
                        this.$message.success("上传成功")
                    }
                })
                this.dialogVisible1 = false;
                setTimeout(() => {
                    this.$router.push({path: "/exam/examPaper", query: {courseId: this.examSign.courseId}})
                }, 500);
            },
            closeCamera() {
                if (this.$refs.takePhotosRef) {
                    this.$refs.takePhotosRef.stopNavigator();
                }
                this.showCamera = false;
            },
            closeSign() {
                this.dialogVisible1 = false;
            }
        }
    }
</script>

<style scoped>
    .exam-container {
        padding: 10px;
        display: flex;
        flex-direction: column;
    }

    .filter-section {
        background: #fff;
        padding: 10px;
        border-radius: 8px;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        flex: 1;
        display: flex;
        flex-direction: column;
        gap: 16px;
    }

    .filter-group {
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .filter-group span {
        font-size: 16px;
        color: #333;
    }

    .tab-group {
        flex-direction: column;
    }

    :deep(.el-tabs__content) {
        flex: 1;
        padding: 16px 0;
        overflow: auto;
    }

    :deep(.el-tab-pane) {
        height: 100%;
    }

    .exam-overview {
        display: flex;
        gap: 20px;
        padding: 8px 0;
    }

    .stats-card {
        flex: 1;
        background: #f8f9fa;
        padding: 24px;
        border-radius: 8px;
        box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
        text-align: center;
        transition: all 0.3s;
    }

    .stats-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
    }

    .stats-card h3 {
        font-size: 16px;
        color: #666;
        margin-bottom: 12px;
    }

    .stat-value {
        font-size: 28px;
        font-weight: bold;
        color: #1890ff;
    }

    .exam-history-list {
        padding: 10px;
    }

    /* 修改分页布局 */
    .el-pagination {
        display: flex;
        justify-content: center;
        margin-top: 10px !important;
    }

    @media (max-width: 768px) {
        .exam-overview {
            flex-direction: column;
        }

        .stats-card {
            margin-bottom: 16px;
        }

        /* 分页样式 */
        .el-pagination {
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
        }

        .el-pagination__total {
            order: 1;
            width: 50%;
            text-align: left;
        }

        .el-pagination__sizes {
            order: 2;
            width: 50%;
            text-align: right;
        }

        .el-pagination .btn-prev,
        .el-pagination .el-pager,
        .el-pagination .btn-next {
            order: 3;
            width: 100%;
            text-align: center;
            margin: 10px 0;
        }

        .el-pagination .el-pagination__jump {
            order: 4;
            width: 100%;
            text-align: center;
        }
    }
</style>
